import Taro from "@tarojs/taro";
// import moment from "moment";
import Tips from "./tips";
import { loginApi, updateUserinfoApi } from '@/api';


/**
 *
 * @param {string} name 错误名字
 * @param {string} action 错误动作描述
 * @param {string} info 错误信息，通常是 fail 返回的
 */



export const isLogin = (event?:any) => {
  if (!Taro.getStorageSync("userInfo")) {
    Taro.getUserProfile({
      desc: '展示用户信息',
      success: function (res) {
        const userInfo = res.userInfo;
        //存储等操作
        Taro.login({
          success: async (res: any) => {
            //获取open_id和session_id
            // let code=await loginCode(res.code);
            loginApi({ code: res.code }).then((res: any) => {
              Taro.setStorageSync('token', res.token);
              // Taro.showToast({
              //   icon: 'none',
              //   title: '登录成功'
              // })
              if(event)event!();
              // Taro.switchTab({ url: '/pages/index/index' });
              const obj = {
                alias: userInfo.nickName,
                avatar: userInfo.avatarUrl,
                gender: userInfo.gender,
                code: res.user.code
              }
              updateUserinfoApi(obj).then((res: any) => {
                Taro.setStorageSync('userInfo', res);
                let pages = Taro.getCurrentPages();;
                let currPage: any = null;
                if (pages.length) {
                  currPage = pages[pages.length - 1];
                };
                currPage.onShow();
              });
            });
          }
        })
      },
      fail(res) {
        Taro.showToast({
          icon: 'none',
          title: '请先授权登录'
        })
      }
    })
  }else{
    if(event)event!();

    return true;
  }

}
export const login = () => {
  Taro.getUserProfile({
    desc: '展示用户信息',
    success: function (res) {
      const userInfo = res.userInfo;
      //存储等操作
      Taro.login({
        success: async (res: any) => {
          //获取open_id和session_id
          // let code=await loginCode(res.code);
          loginApi({ code: res.code }).then((res: any) => {
            Taro.setStorageSync('token', res.token);
            // Taro.switchTab({ url: '/pages/index/index' });
            const obj = {
              alias: userInfo.nickName,
              avatar: userInfo.avatarUrl,
              gender: userInfo.gender,
              code: res.user.code
            }
            updateUserinfoApi(obj).then((res: any) => {
              Taro.setStorageSync('userInfo', res);
              let pages = Taro.getCurrentPages();;
              let currPage: any = null;
              if (pages.length) {
                currPage = pages[pages.length - 1];
              };
              currPage.onShow();
            });
          });
        }
      })
    },
    fail(res) {
      Taro.showToast({
        icon: 'none',
        title: '请先授权登录'
      })
    }
  })
}


export const logError = (name: string, action: string, info?: string | object) => {
  // if (!info) {
  //   info = 'empty'
  // }
  // // let time = formatTime()
  // console.error(new Date(), name, action, info)
  // if (typeof info === 'object') {
  //   info = JSON.stringify(info)
  // }
}
/**
 * 校验手机号是否正确
 * @param phone 手机号
 */
export const verifyPhone = (phone) => {
  const reg = /^1[0-9]{10}$/;
  const _phone = phone.toString().trim();
  let toastStr =
    _phone === ""
      ? "手机号不能为空~"
      : !reg.test(_phone) && "请输入正确手机号~";
  return {
    errMsg: toastStr,
    done: !toastStr,
    value: _phone,
  };
};

//手机号中间4位****
export const dispostPhone = (phone) => {
  if (phone) {
    let reg = /^(\d{3})\d*(\d{4})$/;
    let newPhone = `${phone}`.replace(reg, "$1****$2");
    return newPhone;
  }
};

// 身份证脱敏
export const dispostIdCard = (idCard) => {
  if (idCard) {
    return idCard.replace(/^(.{6})(?:\d+)(.{4})$/, "$1****$2");
  }
  return null;
};

// 校验必填
export const verifyStr = (str, text) => {
  const _str = str.toString().trim();
  const toastStr = _str.length ? false : `请填写${text}～`;
  return {
    errMsg: toastStr,
    done: !toastStr,
    value: _str,
  };
};

// 截取字符串
export const sliceStr = (str, sliceLen) => {
  if (!str) {
    return "";
  }
  let realLength = 0;
  const len = str.length;
  let charCode = -1;
  for (var i = 0; i < len; i++) {
    charCode = str.charCodeAt(i);
    if (charCode >= 0 && charCode <= 128) {
      realLength += 1;
    } else {
      realLength += 2;
    }
    if (realLength > sliceLen) {
      return `${str.slice(0, i)}...`;
    }
  }

  return str;
};

/**
 * JSON 克隆
 * @param {Object | Json} jsonObj json对象
 * @return {Object | Json} 新的json对象
 */
export function objClone(jsonObj) {
  var buf;
  if (jsonObj instanceof Array) {
    buf = [];
    var i = jsonObj.length;
    while (i--) {
      buf[i] = objClone(jsonObj[i]);
    }
    return buf;
  } else if (jsonObj instanceof Object) {
    buf = {};
    for (var k in jsonObj) {
      buf[k] = objClone(jsonObj[k]);
    }
    return buf;
  } else {
    return jsonObj;
  }
}

// 克隆Map
export function mapClone(mapObj) {
  var newMap;
  if (mapObj instanceof Map) {
    newMap = new Map();
    for (let [key, value] of mapObj.entries()) {
      newMap.set(key, value);
    }
    return newMap;
  } else {
    return mapObj;
  }
}

/**
 * @msg: 返回当前页面路由
 */
export const getRouterUrl = (num = 1) => {
  const pages = Taro.getCurrentPages();

  let url = "";
  if (pages.length >= num) {
    const currentPage = pages[pages.length - num];
    url = currentPage.route;
  } else {
    url === "";
  }

  return url;
};




/**
 * 格式化时间
 * @param data
 * @returns {string}
 */
// export function formatTime(data, fmtType = "YYYY-MM-DD HH:mm:ss") {
//   return data ? moment(data).format(fmtType) : "";
// }

/**
 * 处理富文本里的图片宽度自适应
 * 1.去掉img标签里的style、width、height属性
 * 2.img标签添加style属性：max-width:100%;height:auto
 * 3.修改所有style里的width属性为max-width:100%
 * 4.去掉<br/>标签
 * @param html
 * @returns {void|string|*}
 */
export function formatRichText(html = "") {
  let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
    match = match.replace(/style="[^"]+"/gi, "").replace(/style='[^']+'/gi, "");
    match = match.replace(/width="[^"]+"/gi, "").replace(/width='[^']+'/gi, "");
    match = match
      .replace(/height="[^"]+"/gi, "")
      .replace(/height='[^']+'/gi, "");
    return match;
  });
  newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
    match = match
      .replace(/width:[^;]+;/gi, "max-width:100%;")
      .replace(/width:[^;]+;/gi, "max-width:100%;");
    return match;
  });
  newContent = newContent.replace(/<br[^>]*\/>/gi, "");
  newContent = newContent.replace(
    /\<img/gi,
    '<img style="max-width:100%;height:auto;display:block;margin:0;vertical-align: middle;"'
  );
  return newContent;
}


/**
 * 解析url参数
 * @param {*} str xxx=xxx&yyy=yyy
 * @returns {object}
 */
export const parseUrlParams = (str = '') => {
  const obj = {};
  if (!str.trim()) return obj;

  const paramsArr = str.split("&");
  for (let i = 0; i < paramsArr.length; i++) {
    const [key, val] = paramsArr[i].split("=");
    obj[key] = val;
  }

  return obj;
}

